#include <jmutex.h>
#include <assert.h>

JMutex::JMutex():isLock(false)
{
    pthread_mutex_init(&mutex, NULL);
}

void JMutex::lock()
{
    isLock = true;
    pthread_mutex_lock(&mutex);
}

void JMutex::unlock()
{
    isLock = false;
    pthread_mutex_unlock(&mutex);
}

bool JMutex::tryLock(int timeout)
{
    long us = timeout * 1000;
    long remainTime = 0;
    while (remainTime <= us) {
        if(!isLock){
            lock();
            return true;
        }
        usleep(100);
    }

    return false;
}

JMutex::~JMutex()
{
    assert(!isLocking());
    pthread_mutex_destroy(&mutex);
}
